//下降路径最小和
class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int>> dp(m, vector<int>(n));
        for (int j = 0; j < n; j++) {
            dp[0][j] = matrix[0][j];
        }
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = dp[i - 1][j]; // 中间上方
                if (j > 0)
                    dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]); // 左上方
                if (j < n - 1)
                    dp[i][j] = min(dp[i][j], dp[i - 1][j + 1]); // 右上方
                dp[i][j] += matrix[i][j];
            }
        }
         return *min_element(dp[n-1].begin(), dp[n-1].end());
    }
};


//最小路径和

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();

        vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
        dp[0][1] = 0;

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++)
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
        }
        return dp[m][n];
    }
};